package day11.handler.simpleChannelHandler.request;

import day11.handler.simpleChannelHandler.response.ListGroupMembersResponseHandler;
import day11.packet.request.ListGroupMembersRequestPacket;
import day11.packet.response.ListGroupMembersResponsePacket;
import day11.util.session.GroupSession;
import day11.util.session.Session;
import day11.util.session.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chenshijie
 * @date 2024/1/2 16:01
 */

public class ListGroupMembersRequestHandler extends SimpleChannelInboundHandler<ListGroupMembersRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ListGroupMembersRequestPacket listGroupMembersRequestPacket) throws Exception {
        int groupId = listGroupMembersRequestPacket.getGroupId();
        GroupSession groupSession = SessionUtil.getGroupSession(groupId);

        ListGroupMembersResponsePacket listGroupMembersResponsePacket = new ListGroupMembersResponsePacket();
        List<Session> userSessions = groupSession.getUserSessions();
        List<String> userNameList = new ArrayList<>();
        for (Session userSession : userSessions) {
            userNameList.add(userSession.getUserName());
        }

        listGroupMembersResponsePacket.setUserNameList(userNameList);
        listGroupMembersResponsePacket.setGroupId(groupId);
        listGroupMembersResponsePacket.setSuccess();
        ctx.channel().writeAndFlush(listGroupMembersResponsePacket);
    }
}
